package spitfire.ksim.node;

import spitfire.ksim.algorithm.KFuzzyRuleBase;
import spitfire.ksim.data.TSDRequestData;
import spitfire.ksim.data.TSDResponseData;
import spitfire.ksim.data.TSDUpdateData;
import spitfire.ksim.network.KNetAddress;
import spitfire.ksim.network.KNetwork;
import spitfire.ksim.simulator.KJob;
import spitfire.ksim.simulator.KSimDuration;
import spitfire.ksim.simulator.KSimulator;
import spitfire.ksim.util.TPoint;

public class KGateway extends KNode{

	private static int nextID = 0;
	private final int gwId = nextID++;
	private KFuzzyRuleBase fuzzyDb = new KFuzzyRuleBase();
	
	public KGateway(KSimulator simulator, KNetwork network, TPoint location) {
		super(simulator, network, location);
		setDisplayName("Gateway-" + gwId + "|" + getNetAddr());
	}

	public static void resetID() {
		nextID = 0;
	}
	
	public void setRequestAlgorithm(String algoName) {
		fuzzyDb.setRequestAlgorithm(algoName);
	}
	
	public String getRequestAlgorithm() {
		return fuzzyDb.getRequestAlgorithmName();
	}
	
	@Override
	public synchronized void onPacketRecv(KNetAddress srcAddr, Object payload) {
		System.out.println(getDisplayName() + " Recv from " + srcAddr + ": " + payload);
		if (payload instanceof TSDRequestData) {
			TSDRequestData request = (TSDRequestData) payload;
			String sd = fuzzyDb.requestForSD(request.getData());
			if (sd != null) {
				send(srcAddr, new TSDResponseData(sd));
			}
			
		} else if (payload instanceof TSDUpdateData) {
			TSDUpdateData update = (TSDUpdateData) payload;
			fuzzyDb.updateRuleBase(update.getData(), update.getSd(), update.getNodeId());
		}
	}

	@Override
	public void doJob(KJob job) {
		
	}

	@Override
	public KSimDuration getSimDuration() {
		return null;
	}

	public int getGwId() {
		return gwId;
	}

}
